package com.health.system.javacommon.util;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringTool {

	/**
	 * 检测操作系统类型
	 * 
	 * Huanglj
	 * 
	 * @param userAgent
	 * @return
	 */
	public static String getOsInfo(String userAgent) {
		String os = "";
		if (userAgent.indexOf("Win95") > -1
				|| userAgent.indexOf("Windows 95") > -1) {
			os = "Win95";
		} else if (userAgent.indexOf("Win98") > -1
				|| userAgent.indexOf("Windows 98") > -1) {
			os = "Win98";
		} else if (userAgent.indexOf("Win 9x 4.90") > -1
				|| userAgent.indexOf("Windows ME") > -1) {
			os = "Windows ME";
		} else if (userAgent.indexOf("Windows NT 5.0") > -1
				|| userAgent.indexOf("Windows 2000") > -1) {
			os = "Windows 2K";
		} else if (userAgent.indexOf("Windows NT 5.1") > -1
				|| userAgent.indexOf("Windows XP") > -1) {
			os = "Windows XP";
		} else if (userAgent.indexOf("Windows NT 6.0") > -1
				|| userAgent.indexOf("Windows Vista") > -1) {
			os = "Windows Vista";
		} else if (userAgent.indexOf("SunOS") > -1) {
			os = "*inux";
		} else {
			os = "Unknow";
		}
		return os;
	}

	/**
	 * 检测浏览器类型
	 * 
	 * Huanglj
	 * 
	 * @param userAgent
	 * @return
	 */
	public static String getBrowserInfo(String userAgent) {
		String browser = "";
		if (userAgent.indexOf("Opera") > -1) {
			browser = "Opera";
		} else if (userAgent.indexOf("MSIE") > -1) {
			Pattern p = Pattern.compile("MSIE[\\s]([^\\;]*?)\\;",
					Pattern.CASE_INSENSITIVE);
			Matcher m = p.matcher(userAgent);
			while (m.find()) {
				// System.out.println("m.group(0)=" + m.group(0));
				// System.out.println("m.group(1)=" + m.group(1));
				browser = "IE" + m.group(1);
				break;
			}
		} else if (userAgent.indexOf("Gecko") > -1) {
			browser = "Firefox";
		} else if (userAgent.indexOf("Safari") > -1) {
			browser = "Safari";
		} else {
			browser = "Unknow";
		}
		return browser;
	}

	/**
	 * 首字母大写
	 * 
	 * @param str
	 * @return
	 */
	public static String upperCaseFristLetter(String str) {
		return str.substring(0, 1).toUpperCase() + str.substring(1);
	}

	/**
	 * 把一个以逗号分隔的String转成ArrayList
	 */
	public static ArrayList stringToArray(String liststr) throws Exception {
		return stringToArray(liststr, ",");
	}

	/**
	 * 把一个以compart分隔的String转成ArrayList
	 */
	public static ArrayList stringToArray(String liststr, String compart)
			throws Exception {
		try {
			ArrayList temparray = new ArrayList();
			int pos = 0;
			String tempstr = liststr;
			if (tempstr.equals(""))
				return null;
			String temp = null;
			while (tempstr.length() > 0) {
				pos = tempstr.indexOf(compart);
				if (pos < 0) {
					 //注意上转字符串的空格
					temparray.add(tempstr.trim());
					break;
				}
				temp = tempstr.substring(0, pos);
				if (temp != null)
					 //注意上转字符串的空格
					temparray.add(temp.trim());
				tempstr = tempstr.substring(pos + 1);
			}
			return temparray;
		} catch (Exception e) {
			// e.printStackTrace();
			throw e;
		}
	}

	// ==========================================================================//
	// Function strCut
	// 分割字串为数组
	// ==========================================================================//
	public static Integer[] strCut(String as_str, String as_split) {
		Integer[] ls_ret = null, ls_arytmp = null;
		String ls_str, ls_split, ls_tmp = "";
		ls_str = as_str;
		ls_split = as_split;
		int li_pos;
		int li_group = 0;
		int li_orgpos = 0;
		// 计算数组大小
		if (as_str == null)
			return ls_ret;
		if (as_str.equals("")) {
			return ls_ret;
		}

		li_group = 0;
		while (ls_str.length() > 0) {
			li_group++;
			if (ls_ret != null) {
				ls_arytmp = new Integer[ls_ret.length];
				ls_arytmp = ls_ret;
				ls_ret = new Integer[li_group];
				for (int i = 0; i < ls_arytmp.length; i++) {
					ls_ret[i] = ls_arytmp[i];
				}
			} else {
				ls_ret = new Integer[li_group];
			}
			li_pos = ls_str.indexOf(ls_split);
			if (li_pos > 0) {
				ls_ret[li_group - 1] = Integer.valueOf(
						ls_str.substring(0, li_pos)).intValue();
				ls_str = ls_str.substring(li_pos + ls_split.length());
			} else {
				if (!ls_str.equals("")) {
					ls_ret[li_group - 1] = Integer.valueOf(ls_str.trim())
							.intValue();
					ls_str = "";
				}
			}
		}
		return ls_ret;
	}

	/**
	 * 内码转换
	 * 
	 */
	public static String getStr(String str) {
		try {
			String temp_p = str;
			String temp = new String(temp_p.getBytes("ISO-8859-1"), "utf-8");
			return temp;
		} catch (Exception e) {
			e.toString();
		}
		return "null";
	}

	/**
	 * 判断字符串是否为空
	 * 
	 * @return
	 */
	public static boolean isNull(String str) {
		if (null == str) {
			return false;
		} else if ("".equals(str.trim())) {
			return false;
		} else if ("null".equals(str)) {
			return false;
		} else if (str.length() <= 0) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 防止SQL 注入方法
	 * 
	 * @param inj_str
	 * @return
	 */
	public boolean avertAfflux(String inj_str) {
		String str = "'|and|exec|insert|select|delete|update|count|*|%|chr|mid|master|truncate|char|declare|;|or|-|+|,";
		String[] inj_stra = str.split("\\|");
		for (int i = 0; i < inj_stra.length; i++) {
			if (inj_str.indexOf("" + inj_stra[i] + "") >= 0) {
				return true;
			}
		}
		return false;
	}

	public static void main(String[] args) {
		System.out.println("XXXX");
		// StringTool xxx= new StringTool();
		String str = "ERdefa sedlEct er masta;Er d ";
		// boolean bool = xxx.avertAfflux(str);
		// System.out.println("###"+xxx.TransactSQLInjection(str));
		System.out.println(StringTool.replaceStringP(str, "eR", ""));
	}

	/**
	 * 把手机叫转成139****1234
	 */
	public static String getPhoneNumber(String str) throws Exception {
		try {
			if (null != str && !"".equals(str)) {
				str = str.trim();
				str = str.substring(0, 3) + "****"
						+ str.substring(7, str.length());
			}
		} catch (Exception e) {
			// e.printStackTrace();
			throw e;
		}
		return str;
	}
	


	/**
	 * 返回设置的格式（日期时间）
	 * 
	 * @return
	 */
	public static String getDateStr(java.sql.Timestamp date, String sFormat) {
		SimpleDateFormat sdf = new SimpleDateFormat(sFormat);
		String nowTime = sdf.format(date);
		return nowTime;
	}

	/**
	 * 返回现在时间（时间）
	 * 
	 * @return
	 */
	public static String getNowTime() {
		Timestamp inserttiem = new Timestamp(System.currentTimeMillis());
		return getDateStr(inserttiem, "HH:mm");
	}

	/**
	 * 大写字母转小写字母的程序
	 * 
	 * @param upper
	 * @return
	 */
	public static String upperStrToLowerStr(String upper) {
		String lower = "";
		for (int i = 0; i < upper.length(); i++) {
			lower += upperCaseToLowerCase(upper.charAt(i));
		}
		return lower;
	}

	public static char upperCaseToLowerCase(char ch) {
		if (ch >= 65 && ch <= 90) { // 如果是大写字母就转化成小写字母
			ch = (char) (ch + 32);
		}
		return ch;
	}

	/**
	 * 返回是否是特殊字符
	 * 
	 * @return
	 */
	public static boolean isString(String str) {
		String badword = "[^@——，#$'\"\"？“”|~%*！]";
		Pattern pattern = Pattern.compile(badword);
		Matcher matcher = pattern.matcher(str);
		return matcher.find();
	}

	/**
	 * 使用正则表达式实现不区分大小写替换
	 * 
	 * @param source
	 * @param oldstring
	 * @param newstring
	 */
	public static String replaceStringP(String source, String oldstring,
			String newstring) {
		System.out.println("source = " + source + ",oldstring=" + oldstring
				+ ",newstring=" + newstring);
		Matcher m = Pattern.compile(oldstring, Pattern.CASE_INSENSITIVE)
				.matcher(source);
		String result = m.replaceAll(newstring);
		System.out.println("使用正则表达式不区分大小写的替换结果" + result);
		return result;
	}

	/**
	 * 实现不区分大小写替换
	 * 
	 * @param source
	 * @param oldstring
	 * @param newstring
	 */
	public static String replaceString(String source, String oldstring,
			String newstring) {
		String result1 = source.replaceAll("(?i)" + oldstring, newstring); // 大小写不敏感
		return result1;
	}

	/**
	 * 判断是否为数字
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		return pattern.matcher(str).matches();
	}
	
	
	/**
	 * 判断是否为移动号码
	 * @param moblie
	 * @return 
	 * by lqb
	 */
	public static boolean isMobilePhone(String moblie){
		//中国移动134.135.136.137.138.139.150.151.152.157.158.159.187.188 
		Pattern p = Pattern.compile( "^1(3[4-9]|5[012789]|8[78])\\d{8}$");
		Matcher m = p.matcher(moblie);
		
		return m.matches();
	}
	
	/**
	 * 以
	 * @param s    String 源串
	 * @param code String 分割符 一般为,号
	 * @return
	 */
	public static String[] SplitString(String s,String code){
		if(null==s||s.trim().length()<1){
			return null;
		}	
		int length = s.length();
		StringTokenizer commaToker = new StringTokenizer(s, code); 
		String[] result = new String[commaToker.countTokens()]; 
		int k = 0; 
		while (commaToker.hasMoreTokens()) { 
			String tempStr = commaToker.nextToken();
			if(null!=tempStr&&tempStr.trim().length()>0){
				result[k] = tempStr;
				k++;
			}
		}
	    return result;
	}
	

}
